/*
 * InputCapture.c
 *
 *  Created on: Nov 5, 2013
 *      Author: BlackVolt
 */

#include "derivative.h"
#include "Mytypes.h"
#include "InputCapture.h"



/**************************************************************
 *  Name                 : vdfn_InputCapture_Init
 *  Description          : Initialize needed system drivers (system elements) before start application 
 *  Parameters           : none
 *  Return               : none
 *  Critical/explanation : FTM2
 **************************************************************/
void vdfn_InputCapture_Init(){
	
	//Already configurated TMP clock = 24Mhz
	//Sistem Clock Gating Enable
	SIM_SCGC6 |= SIM_SCGC6_TPM2_MASK;
	
	//Select Preescaler(128)
	TPM2_SC |=  TPM_SC_PS(7); // CLK/128 = 187,500Hz 
	
	//Define TPM2 channel 0 as Input Capture and Enable Channel Interrupt
	TPM2_C0SC |= TPM_CnSC_ELSA_MASK | TPM_CnSC_CHIE_MASK;	 
	
	//Define the Max Count
	TPM2_MOD = 0xFFFF;
	
	//Enable the counter
	TPM2_SC |= TPM_SC_CMOD(1);
	
	//Init Variables
	Frecuency_Divider = 187500;
	

}

/**************************************************************
 *  Name                 : vdfn_Interrupt_Handler
 *  Description          : Clear flag and Save the Value of CV then Calculate the Value between 
 *  					   the 2 rissing edges.
 *  Parameters           : none
 *  Return               : none
 *  Critical/explanation : FTM2 Interrupt function
 **************************************************************/
void vdfn_Interrupt_Handler(){
	//Clear Flag
	TPM2_C0SC |= TPM_CnSC_CHF_MASK;
		
	if((TPM2_SC & TPM_SC_TOF_MASK) == 0x80){
		Frec_Flag = 1;
		//Clear Flag
		(void) TPM2_SC;
		TPM2_SC |= TPM_SC_TOF_MASK;
		
		//Save Value Before
		Counter_Backup = Counter_Backup_New;
		//Save Value of CnV
		Counter_Backup_New = TPM2_C0V; 
		//Save Value of CnV
		Counter_Backup_OVF = Counter_Backup_New + 0xFFFF;
		//Calculate the Velocity Value
		Value = Counter_Backup_OVF - Counter_Backup;
	}
		else{
			//Save Value Before
			Counter_Backup = Counter_Backup_New;
			//Save Value of CnV
			Counter_Backup_New = TPM2_C0V; 
			//Calculate the Velocity Value
			Value = Counter_Backup_New - Counter_Backup;
		}
		
		
	}


/**************************************************************
 *  Name                 : vdfn_Save_Data
 *  Description          : Calculate the real "Velocity" of the car
 *  Parameters           : none
 *  Return               : none
 *  Critical/explanation : Each 5 ticks is called
 **************************************************************/

void vdfn_Save_Data(){
		
	Frecuency_Real = Frecuency_Divider / Value;
	

}

